﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdvanceLib.ScriptCore;
using AdvanceLib.ScriptCore.DebugCore;

namespace AdvanceLib.Extension.Root.DebugPasses
{
    public class ParameterValidationPass : CommandPass, IFinalPass
    {
        #region Constructors
        public ParameterValidationPass(RootProvider provider)
        {
            this._host = provider.Host;
            this._commands = new List<ISystemCommand>();
        }
        #endregion

        #region Fields
        private ScriptHost _host;
        private List<ISystemCommand> _commands;
        #endregion

        #region CommandPass Members
        public override void Pass(DebugResult result, string input)
        {
            if (this.CurrentLinePartIndex == 0 &&
                this.CurrentLine.StartsWith(this._host.SystemCommandInitialization))
            {
                this._commands = this._host.ExtensionManager.GetSystemCommandsByName(input.Substring(this._host.SystemCommandInitialization.Length));
            }
            else if (this._commands != null)
            {
                foreach (ISystemCommand command in this._commands)
                {
                    if (command.ExpectedParameters == this.CurrentLine.Count(c => c == ' '))
                    {
                        bool valid = command.DebugParameter(this.CurrentLinePartIndex - 1, input);

                        if (!valid)
                        {
                            result.Errors.Add(new DebugError()
                            {
                                Line = this.CurrentLineIndex,
                                Message = "Parameter " + this.CurrentLinePartIndex + " has the wrong input format. "
                            });
                        }
                        break;
                    }
                }
            }
        }
        #endregion

        #region IFinalPass Member
        public void FinalPass(DebugResult result)
        {
            this._commands = new List<ISystemCommand>();
        }
        #endregion
    }
}
